package com.lap.auth.application.menu;

import com.lap.auth.domain.menu.repository.MenuApiRepository;
import com.lap.auth.domain.menu.service.MenuValidator;
import com.lap.auth.domain.menu.valueobject.MenuApi;
import java.util.List;
import java.util.Set;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@RequiredArgsConstructor
@Service
public class MenuApiAppService {

  private final MenuValidator menuValidator;
  private final MenuApiRepository menuApiRepository;

  @Transactional(rollbackFor = Exception.class)
  public void replaceMenuApis(Integer menuId, Set<String> apiSet) {
    menuValidator.assertMenuExists(menuId);
    menuApiRepository.deleteByMenuId(menuId);
    if (CollectionUtils.isNotEmpty(apiSet)) {
      List<MenuApi> relations = apiSet.stream().map(code -> new MenuApi(menuId, code)).toList();
      menuApiRepository.saveAll(relations);
    }
  }

  public List<String> queryMenuApisByMenuId(Integer menuId) {
    menuValidator.assertMenuExists(menuId);
    return menuApiRepository.findByMenuId(menuId);
  }
}
